#! /usr/local/bin/python3
# coding=utf-8

import os
import re
import argparse
import sys

def get_file_name(line):
    # line = '  * [前言](intro.md）'
    content = line.strip()
    pattern = r'\((.*?)\)'
    result = re.search(pattern,content)
    # print(dir(result))
    if result:
        return result.group(1)
    else:
        raise ValueError("文件格式有误！")

def merge():

    parser = argparse.ArgumentParser()
    parser = argparse.ArgumentParser(description = '合并多个markdown文件并转化为docx文件')
    parser.add_argument('--contents','-c',help='目录文件，用来指定合并对象',default='contents.md')
    parser.add_argument('--source','-s',help='合并后的文件名',default='all.md')
    parser.add_argument('-td','--targerDictionary',help='目标文件所在目录',default='~/Documents/我的坚果云/')
    parser.add_argument('-r','--referenceDoc',help='word模板文件',default='OfficalDocument.docx')
    parser.add_argument('-t','--target',help='目标文件名',default='out.docx')
    args = parser.parse_args()

    cwd = os.getcwd() + '/'

    try:
        file = open(cwd + args.contents)
    except OSError as e:
        print('当前目录中没有contents文件',e)
        return

    try:
        fo = open(cwd + args.source, 'w')
    except OSError as e:
        print('无法在当前目录创建合并文件',e)
        return

    for line in file:
        fi = open(cwd + get_file_name(line))
        while True:
            s = fi.read(16*1024)
            if not s:
                fo.write('\n')
                break
            fo.write(s)
        fi.close()
    file.close()
    fo.close()

    os.system('pandoc --reference-doc=' + args.targerDictionary + args.referenceDoc + ' -s ' + args.source + ' -o ' + args.targerDictionary + args.target)

if __name__=="__main__":
    merge()
